package com.wwz.controller;

import com.wwz.pojo.FileInfo;
import com.wwz.service.IFileService;
import com.wwz.util.JobUtils;
import com.wwz.util.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.List;

/**
 * 文件控制器
 * @date 2022/2/16 16:59
 */
@RestController
@RequestMapping("/centre/file")
@Api(tags = "文件控制层")
public class FileController {

    @Resource
    private IFileService fileService;

    @ApiOperation("上传文件")
    @PostMapping("/upload")
    public Result upload(MultipartFile file,String dataId){
        fileService.upload(file,dataId);
        return Result.ok("上传成功!");
    }


    @ApiOperation("下载文件")
    @GetMapping("/download/{fileId}")
    public Result download(@PathVariable String fileId, HttpServletResponse response){
        FileInfo fileInfo = fileService.getById(fileId);
        JobUtils.download(response,JobUtils.getFile(fileInfo));
        return Result.ok();
    }


    @ApiOperation("删除文件")
    @DeleteMapping("/deleteFile/{fileId}")
    public Result deleteFile(@PathVariable String fileId){
       fileService.deleteFile(fileId);
        return Result.ok();
    }


    @ApiOperation("查询所有文件")
    @GetMapping("/list")
    public Result fileList(){
        List<FileInfo> list = fileService.list();
        return Result.ok(list);
    }

    @ApiOperation("根据业务id获取文件")
    @GetMapping("/getById/{id}")
    public Result<FileInfo> getByDateId(@PathVariable String id){
        FileInfo byId = fileService.getByDateId(id);
        return Result.ok("ok",byId);
    }

    @ApiOperation("获取头像")
    @GetMapping("/getPhoto/{id}")
    public Result getPhoto(HttpServletResponse response,@PathVariable String id){
        FileInfo fileInfo = fileService.getByDateId(id);
        if (fileInfo != null){
            JobUtils.download(response,JobUtils.getFile(fileInfo));
            return Result.ok();
        }
        return null;
    }


}
